#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "misc.h"

int main(int argc, char **argv){
	char buffer[80]= {0};
	char retStr[80] = {0};
	char hexStr[160] = {0};
	char *toker = NULL;
	FILE *file = NULL;
	BasicHashFunctionPtr h = NULL;
	int hsize = 0;

	/*check the no. of param. the user entered*/
	if (argc != 3) {
		fprintf(stderr, "Error: Usage create_authentication <hash function name> <filename to create>\n");
		return 0;
	}

	/*parse the hash function name and assign h appropriately*/
	parseHashFunction(argv[1], &h, &hsize);
	if (h == NULL){
		fprintf(stderr, "Error: Hash %s is not supported\n", argv[1]);
		return 0;
	}

	if ((file = fopen(argv[2], "r")) != NULL){
		fclose(file);
		fprintf(stderr, "Error: File %s already exist\n", argv[2]);
		return 0;
	}

	/*check if something is wrong with the file*/
	if (!(file = fopen(argv[2], "w"))){
		perror(argv[1]);
		return 0;
	}

	fprintf(file, "%s\n", argv[1]);

	while (1){
		printf(">>");
		readBuffer(buffer);
		if (strcmp(buffer,"quit") == 0) 
			break;
		else if (*buffer == '\0')
			continue;
		else if (checkBuffer(buffer) == 0) {
			fprintf(stderr, "Error: Commands are either quit or <user name>tab<password>.\n");
			continue;
		}
		toker = strtok(buffer, "\t");		
		fprintf(file, "%s\t", toker);
		toker = strtok(NULL, "\t");
		cryptHash(*h, toker, (unsigned char *)retStr);
		binary2hexa((unsigned char *)retStr, hsize, hexStr, 160);
		fprintf(file, "%s\n", hexStr);
	}
	fclose(file);
	return 0;
}
